package com.songcha.library_common.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.graphics.drawable.toBitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.songcha.library_common.R

class GlideUtil {
    interface IOnGlideLoadListener{
        fun onGlideLoadSuccess(bitmap:Bitmap)
    }

    companion object{
        @JvmStatic
        fun loadNetImage(img:ImageView,url:String?,diskCacheStrategy:DiskCacheStrategy = DiskCacheStrategy.NONE){
            if(url.isNullOrBlank()) return
            Glide.with(img.context).load(url)
                //.error(R.mipmap.common_image_placeholder)
                .error(R.drawable.common_bg_image_error)
                .diskCacheStrategy(diskCacheStrategy)
                .into(img)
        }

        @JvmStatic
        fun loadCustomImageView(iv: ImageView, url:String, width:Int,
                                diskCacheStrategy:DiskCacheStrategy = DiskCacheStrategy.AUTOMATIC, onGetLayoutParams:(width:Int,height:Int)-> ViewGroup.LayoutParams, onHeight:((height:Int)->Unit)? = null){
            if(url.isNullOrBlank()) return
            val target = object : CustomViewTarget<ImageView, Bitmap>(iv){
                override fun onLoadFailed(errorDrawable: Drawable?) {

                }

                override fun onResourceCleared(placeholder: Drawable?) {

                }

                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    val height = (width / (resource.width * 1.0f / resource.height)).toInt()
                    //val lp = (P as ViewGroup).LayoutParams(width,height)
                    iv.layoutParams = onGetLayoutParams(width,height)
                    iv.setImageBitmap(resource)
                    if(onHeight != null)
                        onHeight(height)
                }

            }
            Glide.with(iv.context).asBitmap().load(url)
                .diskCacheStrategy(diskCacheStrategy)
                .into(target)
        }
    }
}